package com.jcodecraeer.huqs;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;

import com.apkfuns.logutils.LogUtils;
import com.jcodecraeer.core.net.IAPIService;
import com.jcodecraeer.core.net.RetrofitManager;
import com.jcodecraeer.huqs.postdetail.PostDetailActivity;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.UnsupportedEncodingException;

import cz.msebera.android.httpclient.Header;
import retrofit2.Callback;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText mEditLoginName, mEditLoginPassword;
    private IAPIService mService;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        mService = RetrofitManager.getInstance(getApplication(), true).getRetrofit().create(IAPIService.class);
        findView();
    }

    private void findView() {
        findViewById(R.id.btn_login).setOnClickListener(this);
        findViewById(R.id.btn_logout).setOnClickListener(this);
        findViewById(R.id.btn_user_info).setOnClickListener(this);
        findViewById(R.id.btn_post_detail).setOnClickListener(this);
        mEditLoginName = (EditText) findViewById(R.id.ed_login_name);
        mEditLoginPassword = (EditText) findViewById(R.id.ed_login_password);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                String name = mEditLoginName.getText().toString().trim();
                String password = mEditLoginPassword.getText().toString().trim();
                mService.login(name, password).enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(retrofit2.Call<String> call, retrofit2.Response<String> response) {
                        Document doc = Jsoup.parseBodyFragment(response.body());
                        Elements script = doc.getElementsByTag("script").eq(0);
                        StringBuffer msg = new StringBuffer(script.toString().split("document.write")[3]);
                        msg.delete(0, 2).delete(msg.length() - 5, msg.length());
                        Toast.makeText(MainActivity.this, "" + msg, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailure(retrofit2.Call<String> call, Throwable t) {
                        LogUtils.e(t.getLocalizedMessage());
                    }
                });
                break;
            case R.id.btn_logout:
                mService.logOut().enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(retrofit2.Call<String> call, retrofit2.Response<String> response) {
                        Document doc = Jsoup.parseBodyFragment(response.body());
                        Elements script = doc.getElementsByTag("script").eq(0);
                        StringBuffer msg = new StringBuffer(script.toString().split("document.write")[3]);
                        msg.delete(0, 2).delete(msg.length() - 5, msg.length());
                        Toast.makeText(MainActivity.this, "" + msg, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailure(retrofit2.Call<String> call, Throwable t) {
                        LogUtils.e(t.getLocalizedMessage());
                    }
                });
                break;
            case R.id.btn_user_info:
                mService.userInfo().enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(retrofit2.Call<String> call, retrofit2.Response<String> response) {
                        LogUtils.d(response.body());

                    }

                    @Override
                    public void onFailure(retrofit2.Call<String> call, Throwable t) {
                        LogUtils.e(t.getLocalizedMessage());
                    }
                });
                break;
            case R.id.btn_post_detail:
//                Intent intent=new Intent(this, PostDetailActivity.class);
//                startActivity(intent);
//                http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2017/0413/7823.html (169ms）
//
//                AsyncHttpClient client = new AsyncHttpClient();
//                client.get("http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2017/0413/7823.html", new AsyncHttpResponseHandler() {
//
//                    @Override
//                    public void onStart() {
//                        // called before request is started
//                    }
//
//                    @Override
//                    public void onSuccess(int statusCode, Header[] headers, byte[] response) {
//                        // called when response HTTP status is "200 OK"
//                        LogUtils.d(new String(response,"GBK"));
//                    }
//                    @Override
//                    public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
//                        // called when response HTTP status is "4XX" (eg. 401, 403, 404)
//                    }
//
//                    @Override
//                    public void onRetry(int retryNo) {
//                        // called when request is retried
//                    }
//                });
                mService.postDetail("a/chengxusheji/java/2017/0109/6960.html").enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(retrofit2.Call<String> call, retrofit2.Response<String> response) {
//                        if (response.body() != null) {
//                            try {
//                                String html = new String(response.body().getBytes(), "gbk");
//                                LogUtils.d(html);
//                            } catch (UnsupportedEncodingException e) {
//                                e.printStackTrace();
//
//                            }
//                            }else{
//                                Toast.makeText(MainActivity.this, "数据获取失败", Toast.LENGTH_SHORT).show();
//                            }
//

                        LogUtils.d(response.body());
                        }
                        @Override
                        public void onFailure (retrofit2.Call < String > call, Throwable t){
                            LogUtils.e(t.getLocalizedMessage());
                        }
                    }

                    );
                    break;
                }


        }
    }
